<template>
  <div class="login-contain">
    <div ref="message" class="message" v-if="showMessage">
      <span ref="error">{{ message }}</span>
    </div>
    <div class="inner-text">
      <p>
        <input class="block" ref="username" type="text" value="zzjw" placeholder="账号">
      </p>
      <p>
        <input class="block" ref="password" type="password" value="123456" placeholder="密码">
      </p>
    </div>
    <div class="type">
      <select class="block" name="type" id="0" ref="type">
        <option value="0">普通住户</option>
        <option value="1">超级管理员</option>
        <option value="2">楼栋管理员</option>
      </select>
    </div>
    <div class="login-button">
      <input class="block" type="button" value="登陆" @click="upload">
      <br>
      <input class="block" type="button" value="没有账号？点击注册" @click="$emit('register')">
    </div>
  </div>
</template>

<script>

import axios from "axios";
import {HOST} from "@/utils/constant";

export default {
  name: "LoginBlock",
  data() {
    return {
      showMessage: false,
      message: '',
    }
  },
  methods: {
    upload() {
      const username = this.$refs.username.value;
      const password = this.$refs.password.value;
      if (username === '' || password === '') {
        this.showMessage = true;
        this.message = '账号或密码不能为空';
        return;
      }

      const params = new URLSearchParams();
      params.append('username', username);
      params.append('password', password);
      params.append('type', this.$refs.type.selectedIndex);
      axios.post(HOST + '/doLogin', params, {
        timeout: 5000,
      }).then(response => {
        console.log(response.data);
        if (response.data.data === '登录账号或密码不正确！请核对后再登录！') {
          this.message = response.data.data;
          this.showMessage = true;
          return;
        }
        sessionStorage.setItem('username', username);
        sessionStorage.setItem('type', this.$refs.type.selectedIndex);
        sessionStorage.setItem('password', password);
        sessionStorage.setItem('userId', response.data.data.userId);
        sessionStorage.setItem('houseId', response.data.data.houseId);
        sessionStorage.setItem('managerId', response.data.data.managerId);
        this.$emit('loginSuccess');
      }).catch(err => {
        this.message = '服务器崩溃';
        this.showMessage = true;
        console.log(err);
      })

    }
  }
}
</script>

<style scoped>


.login-contain {
  width: 500px;
  height: 300px;
  background-color: #f6fafa;
  background-image: url("../assets/login.jpg");
}


.inner-text {
  position: absolute;
  left: 150px;
  top: 30px;
}

.type {
  position: absolute;
  left: 150px;
  top: 150px;
}

.login-button {
  position: absolute;
  left: 150px;
  top: 200px;
}

.block {
  width: 200px;
  margin-top: 10px;
}

.message {
  font-size: 15px;
  color: #ff0000;
  position: absolute;
  left: 180px;
  top: 10px;
}
</style>